import { PageContainer } from '@ant-design/pro-layout';
import ProForm, {
  ProFormDigit,
  ProFormGroup,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import type { FormInstance } from 'antd';
import { Card, message, Spin } from 'antd';
import { history } from 'umi';
import { useEffect, useRef, useState } from 'react';
import type { HostInfoEntity, HostInfoField } from './service';
import { getHostInfo, saveHostInfo } from './service';
import FooterButton from '@/components/FooterButton';
import type { Rule } from 'rc-field-form/lib/interface';

export const rules: Record<HostInfoField, Rule[]> = {
  id: [{ required: true, message: '请输入 主键', type: 'number' }],
  name: [{ required: true, message: '请输入 主机名称', type: 'string' }],
  mac: [{ required: true, message: '请输入 MAC 地址', type: 'string' }],
  gateway: [
    { required: true, message: '请输入 网关地址（默认：255.255.255.255）', type: 'string' },
  ],
  port: [{ required: true, message: '请输入 端口（默认：9）', type: 'number' }],
  remark: [],
  deleted: [],
  createdTime: [],
  updatedTime: [],
};

export const defaultValue: HostInfoEntity = {
  createdTime: undefined,
  deleted: false,
  gateway: '255.255.255.255',
  id: undefined,
  mac: undefined,
  name: undefined,
  port: 9,
  remark: undefined,
  updatedTime: undefined,
};

export default () => {
  const formRef = useRef<FormInstance>();
  const [currentData, setCurrentData] = useState<any>({ ...defaultValue });
  const [loading, setLoading] = useState<boolean>(false);
  useEffect(() => {
    // 先从 state 中拿数据，然后再从 query 中拿数据，query 中的数据会覆盖 state 的数据
    const params: Struct.FormPageParams = { ...history.location.state, ...history.location.query };
    if (params.primaryKey) {
      setLoading(true);
      getHostInfo(params.primaryKey)
        .then((data) => {
          setCurrentData(data);
          formRef.current?.setFieldsValue(data);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, []);
  return (
    <PageContainer
      header={{
        breadcrumb: {},
        onBack: history.goBack,
      }}
    >
      <Card>
        <Spin spinning={loading}>
          <ProForm
            submitter={{
              render: (_, dom) => <FooterButton>{dom}</FooterButton>,
            }}
            formRef={formRef}
            onFinish={async (values) => {
              setLoading(true);
              const hide = message.loading('正在提交');
              return saveHostInfo({ ...currentData, ...values })
                .then(() => {
                  history.goBack();
                })
                .finally(() => {
                  hide();
                  setLoading(false);
                });
            }}
            initialValues={currentData}
          >
            <ProFormText
              name="name"
              label="主机名称"
              placeholder="请输入 主机名称"
              rules={rules.name}
            />
            <ProFormGroup>
              <ProFormText
                name="mac"
                label="MAC 地址"
                placeholder="请输入 MAC 地址"
                rules={rules.mac}
              />
              <ProFormText
                name="gateway"
                label="网关地址"
                placeholder="请输入 网关地址"
                help="网关地址（默认：255.255.255.255）"
                rules={rules.gateway}
              />
              <ProFormDigit
                name="port"
                label="端口"
                placeholder="请输入 端口"
                help="端口（默认：9）"
                rules={rules.port}
                min={0}
                fieldProps={{ precision: 0 }}
              />
            </ProFormGroup>
            <ProFormTextArea
              name="remark"
              label="备注"
              placeholder="请输入 备注"
              rules={rules.remark}
            />
            {/** <ProFormRadio.Group
             width="sm"
             name="表单字段名称"
             label="字典类型名称"
             request={getDicTypeValue}
             params={{ dicType: '字典类型代码' }}
             rules={rules.表单规则}
             />
             <ProFormSelect
             width="sm"
             name="表单字段名称"
             label="字典类型名称"
             placeholder="请输入 字段说明"
             request={getDicTypeValue}
             params={{ dicType: '字典类型代码' }}
             rules={rules.表单规则}
             /> */}
          </ProForm>
        </Spin>
      </Card>
    </PageContainer>
  );
};
